import pandas as pd
import scipy.stats as stats
import matplotlib.pyplot as plt
import numpy as np

file = r"data/boston_housing.csv"
df = pd.read_csv(file)
prices = df.values[:,-1]
# 总体均值
population_mean = prices.mean()
print(f"总体均值: {population_mean:.2f}")
# 可视化价格分布
# plt.hist(prices, bins=30, edgecolor='k')
# plt.xlabel("Price")
# plt.ylabel("Frequency")
# plt.title("Distribution of Boston Housing Prices")
# plt.show()
# 抽样
n = 100
np.random.seed(1)
# 从 prices 中无放回地随机抽取100个样本（replace=False）
samples = np.random.choice(prices,n,replace=False)

# 样本均值和标准差
x_bar = samples.mean()
# 样本标准差
s = samples.std(ddof=1)

# 单样本 t 检验
t_stat,p_value=stats.ttest_1samp(samples,popmean=prices.mean())
print(f"t检验p值:{p_value:.4f}") # p>0.05说明抽样无显著偏差
# 构造95的置信区间
t_low = stats.t.ppf(0.025,n-1)
t_upper = stats.t.ppf(0.975,n-1)
# print(t_low,t_upper)
u_low = x_bar-t_upper*s/(n**0.5)
u_upper = x_bar-t_low*s/(n**0.5)
print(u_low,u_upper)
